package cn.wh.xwm.controller.action;

import java.util.Date;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Transaction;

import cn.wh.xwm.common.util.Constant;
import cn.wh.xwm.hibernate.dao.Userinfo;
import cn.wh.xwm.hibernate.dao.UserinfoDAO;

public class LoginAction extends BaseAction {
	private String username;
	private String password;
	/**
	 * 登陆
	 * @return
	 */
	public String login(){
		String tag;
		UserinfoDAO dao = new UserinfoDAO();
		Userinfo userinfo = new Userinfo();
		userinfo.setUsername(username);
		userinfo.setPassword(password);
		userinfo = dao.findByUsernameAndPassword(userinfo);
		if(userinfo==null){
			tag = "passworderror"; 
		}else{
			Transaction ts = dao.getSession().getTransaction();
			ts.begin();
			userinfo.setLastlogin(new Date());
			dao.save(userinfo);
			ts.commit();
			ServletActionContext.getRequest().getSession().setAttribute(Constant.USER_SESSION, userinfo);
			if(userinfo.getUsername().equals(Constant.ADMIN)){
				tag ="goAdminPage";
			}else{
				if(userinfo.getRole()==1){
					tag = "goPmPage";
				}else{
					tag = "goSalesPage";
				}
			}
		}
		dao.getSession().close();
		return tag;
	}
	
	/**
	 * 登出
	 * @return
	 */
	public String logout(){
		ServletActionContext.getRequest().getSession().removeAttribute(Constant.USER_SESSION);
		return "logoutSuccess";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
	
}
